package cn.edu.bs.web.controller;

import cn.edu.bs.domain.UserExample;
import cn.edu.bs.service.UserService;
import cn.edu.bs.web.request.user.UserFormCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class UserController extends BaseController {

    private final String SIGN_PAGE = "user/sign";
    private final String LOGIN_PAGE = "admin/login";

    @Autowired
    private UserService userService;

    @GetMapping("/sign")
    public String toSignPage() {
        return "user/sign";
    }

    @PostMapping("/sign")
    public String doSign(
            UserFormCommand command,
            Model model
    ) {
        String username = command.getUsername();
        String password = command.getPassword();

        if (username == null || username.trim().equals("")) {
            model.addAttribute("error", "用户名不能为空");
            return SIGN_PAGE;
        }
        if (password == null || password.trim().equals("")) {
            model.addAttribute("error", "密码不能为空");
            return SIGN_PAGE;
        }
        UserExample example = new UserExample();
        example.createCriteria().andUsernameEqualTo(username);
        if ("admin".equals(username) || userService.countByExample(example) != 0) {
            model.addAttribute("error", "用户名已存在");
            return SIGN_PAGE;
        }
        userService.insert(userService.transformCommandToEntity(command));
        model.addAttribute("success", "注册成功，请使用账号 " + username + " 进行登陆");
        return LOGIN_PAGE;
    }
}
